package com.wlyuan.open.scanner.utils;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.wlyuan.open.scanner.constant.Constants;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Optional;

/**
 * @author lijing
 * @description
 */
public class DateUtils {

    private final static DateTimeFormatter PATTERN = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    public static Integer toDays(LocalDateTime start, LocalDateTime end) {
        if (start == null || end == null) {
            return Constants.INVALID_NUMBER_ZERO;
        }
        return between(start, end).intValue();
    }

    public static Long between(LocalDateTime start, LocalDateTime end) {
        Date startTime = toDate(start);
        Date endTime = toDate(end);
        return Optional.ofNullable(DateUtil.between(startTime, endTime, DateUnit.DAY)).orElse(0L);
    }

    public static Date toDate(LocalDateTime localDateTime) {
        return Optional.ofNullable(localDateTime).map(d -> Date.from(d.atZone(ZoneId.systemDefault()).toInstant())).orElse(null);
    }

    public static LocalDateTime dateTimeDefaultToNull(LocalDateTime localDateTime) {
        return Optional.ofNullable(localDateTime).filter(x -> !Constants.YEAR.equals(x.getYear())).orElse(null);
    }

    public static String chineseMonthDatePattern(LocalDateTime localDateTime) {
        return DateUtil.format(localDateTime, "yyyy年MM月");
    }

    public static LocalDateTime defaultDateTime() {
        return LocalDateTime.parse(Constants.DEFAULT_DATE_TIME, PATTERN);
    }

    public static LocalDateTime strToDateTime(Long epochMilli) {
        return LocalDateTime.ofInstant(Instant.ofEpochMilli(epochMilli), ZoneId.systemDefault());
    }

    public static LocalDateTime toLocalDateTime(LocalDateTime localDateTime) {
        return LocalDateTime.parse(PATTERN.format(localDateTime), PATTERN);
    }

    public static LocalDateTime minLocalDateTime(LocalDateTime startTime, LocalDateTime endTime) {
        return startTime.isAfter(endTime) ? endTime : startTime;
    }
}
